import {ethers} from 'ethers'

const staking_addr = "0x4B21bbc60BC2175f08a0c7d4a2D345aeB8581640"
const web_addr = "0xfA59b6f70D909535deB1d3c2424ba70bf1408087"
const ADDRESS0 = '0x0000000000000000000000000000000000000000'
const ROUTER = '0x10ED43C718714eb63d5aA57B78B54704E256024E'
const USDT = '0x55d398326f99059fF775485246999027B3197955'

const IStaking = [
	"function stake(uint160 _amount, uint256 amountOutMin) external",
	"function balances(address) external view returns (uint256)",
	"function unstake() external returns (uint256)",
	"function maxStakeAmount() external view returns (uint256)",
	"function balanceOf(address account) public view returns (uint256 balance)",
]

const IWEB =[
       'function transfer( address recipient, uint256 amount ) external returns (bool)',
        'function allowance(address owner, address spender) external view returns (uint256)',
        'function approve(address spender, uint256 amount) external returns (bool)',
        'function decimals() external pure returns (uint8)',
        'function balanceOf(address account) external view returns (uint256)',
]

const swapABI =[
		"function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts)",
        "function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts)",
    ]

const connectMetamask = async () => {
    if (!window.ethereum) return {error: true,msg:"Please link to the wallet environment for use"}
    let addressArray;
    try {
        addressArray = await window.ethereum.request({
            method: "eth_requestAccounts",
        });
        if (addressArray.length !== 0) {
            return addressArray[0];
        }
    } catch (connectError) {
        return {
			error: true,
            msg: connectError,
        };
    }
};

const buy = async (amount) =>{
	if (!window.ethereum) return {error: true,msg: 'please connect wallet'}
	const provider = new ethers.providers.Web3Provider(window.ethereum)
	const account = await connectMetamask()
	if(typeof account !== 'string') return account
	const value = ethers.utils.parseEther(amount)

	const signer = provider.getSigner()

    const token = new ethers.Contract(USDT, IWEB, signer)
    const allowance = await token.allowance(account, staking_addr)

    if (allowance.lt(value)) {
        const tx = await token.approve(staking_addr, ethers.constants.MaxUint256)
        await tx.wait()
    }
	
	const stake = new ethers.Contract(staking_addr, IStaking, signer)
	
    const router = new ethers.Contract(ROUTER, swapABI, provider)
    const [, amount1] = await router.getAmountsOut(value.mul('50').div('100'), [USDT, web_addr])
    console.log(amount1);
	const pMin = amount1.mul(98).div(100);
	
	const tx = await stake.stake(value,pMin)
	const r = await tx.wait()
	return r
}

const getEarned = async () =>{
	if (!window.ethereum) return {error: true,msg: 'please connect wallet'}
	const provider = new ethers.providers.Web3Provider(window.ethereum)
	const account = await connectMetamask()
	if(typeof account !== 'string') return account
	
	const stake = new ethers.Contract(staking_addr, IStaking, provider)
	const earn = await stake.balanceOf(account)
	const res2 = ethers.utils.formatEther(earn)
	return res2
}
const maxStake = async () =>{
	if (!window.ethereum) return {error: true,msg: 'please connect wallet'}
	const provider = new ethers.providers.Web3Provider(window.ethereum)
	const account = await connectMetamask()
	if(typeof account !== 'string') return account
	
	const stake = new ethers.Contract(staking_addr, IStaking, provider)
	const earn = await stake.maxStakeAmount()
	const res2 = ethers.utils.formatEther(earn)
	return res2
}

const unstake = async () =>{
	if (!window.ethereum) return {error: true,msg: 'please connect wallet'}
	const provider = new ethers.providers.Web3Provider(window.ethereum)
	const account = await connectMetamask()
	if(typeof account !== 'string') return account
	
	const signer = provider.getSigner()
	const stake = new ethers.Contract(staking_addr, IStaking, signer)
	const tx = await stake.unstake()
	const r = await tx.wait()
	return r
}



export {
connectMetamask,
buy,
unstake,
getEarned,
ADDRESS0,
maxStake
}